package com.zys.sac.core.filter;

import com.zys.sac.core.constant.RequestParam;
import com.zys.sac.core.constant.RequestStatus;
import com.zys.sac.core.util.ServletResponseUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Optional;

/**
 * 验证码过滤器抽象类，如果需要在登录的时候增加验证码校验，可以通过实现该抽象类
 *
 * Created by zhongjunkai on 2022/3/31.
 */
public abstract class VerifyCodeFilter extends OncePerRequestFilter {

    @Autowired
    private SacCheckFilter sacCheckFilter;

    /**
     * 获取用于比对的验证码，因为不同的系统实现方式可能不一样，有些会保存在redis，有些通过session保存，因此交给使用者自行实现
     *
     * @param request
     * @return
     */
    protected abstract Object getGenCode(HttpServletRequest request);

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String loginPath = sacCheckFilter.loginPath();
        String targetPath = request.getRequestURI().substring(request.getContextPath().length());
        //如果访问的是登录接口，才校验验证码
        if(StringUtils.hasText(loginPath) && loginPath.equals(targetPath)) {
            //获取登录请求中传递的验证码
            String verifyCode = request.getParameter(RequestParam.VERIFY_CODE);
            if(!StringUtils.hasText(verifyCode)) {
                ServletResponseUtils.render(response, ServletResponseUtils.result(RequestStatus.VERIFYEMPTY.getCode(), RequestStatus.VERIFYEMPTY.getMsg()));
                return;
            }
            //将请求中的验证码与生成的验证码进行比较，因为生成验证这部分由用户自行实现，这里提供了抽象方法
            if(verifyCode.equalsIgnoreCase(Optional.ofNullable(getGenCode(request)).orElse("").toString())) {
                filterChain.doFilter(request, response);
                return;
            }
            ServletResponseUtils.render(response, ServletResponseUtils.result(RequestStatus.VERIFYERROR.getCode(), RequestStatus.VERIFYERROR.getMsg()));
            return;
        } else {
            filterChain.doFilter(request, response);
        }
    }
}
